<script setup>
import {reactive, ref} from "vue";
import {$ajax, apiUrl, uploadImageUrl} from "@/utils/ajax";
import router from "@/router";

const login = ref(null)
const loginForm = reactive({username: '', password: '', captcha: ''})
const captchaImg = ref(`${uploadImageUrl}captcha.html?$_=${Math.random()}`)
const loginRules = reactive({
  username: [
    {required: true, message: '请输入账号', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'}
  ],
  captcha: [
    {required: true, message: '请输入验证码', trigger: 'blur'}
  ]
})
const loading = ref(false)
const submitForm = (refs) => {
  console.log(refs)
  refs.validate(valid => {
    loading.value = valid
    if (valid) {
      console.log(process.env.VUE_APP_API_URL)
      $ajax.post(`${apiUrl}authorization/adminLogin`, loginForm).then(({data: {result}}) => {
        loading.value = false
        let res = {
          id: result.id,
          expireTime: result.verify_time,
          token: result.login_token
        }
        window.localStorage.setItem("account", JSON.stringify(res))
        router.replace({name: 'home'})
      }).catch(() => {
        loading.value = false
        captchaImg.value = `${uploadImageUrl}captcha.html?$_=${Math.random()}`
      })
    }
  })
}
</script>

<template>
  <div class="login-box">
    <el-card class="login-card">
      <template #header>
        管理员登录
      </template>
      <el-form ref="login" :model="loginForm" :rules="loginRules" @keyup.enter="submitForm(login)">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入账号" autofocus/>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" placeholder="请输入密码" type="password"/>
        </el-form-item>
        <el-form-item prop="captcha">
          <el-input v-model="loginForm.captcha" placeholder="请输入验证码">
            <template #suffix>
              <el-image :src="captchaImg" class="captcha-img"
                        @click="captchaImg = `${uploadImageUrl}captcha.html?$_=${Math.random()}`"/>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(login)" round :loading="loading">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped lang="less">
.login-box {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: #f5f5f5;

  .login-card {
    width: 350px;
    border-radius: 12px;
    margin: 15vh auto;

    .el-input {
      /deep/ .el-input__wrapper {
        box-shadow: none;
        border-radius: 0;
        border-bottom: var(--el-border);
      }
    }

    .el-image {
      height: 30px;
      cursor: pointer;
    }

    .el-button {
      width: 100%;
    }
  }
}
</style>
